package com.atguigu.yygh.hosp.testmongo;


import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/TestMongo2")
public class TestMongo2 {
    @Autowired
    private UserRepository userRepository;
    @GetMapping("create")
    public void createUser() {
        User user=new User();
        user.setName("mongo2");
        user.setAge(21);
        user.setEmail("1643532388@qq.com");
        User save = userRepository.save(user);
        System.out.println(save);
    }
    //查询所有
    @GetMapping("findAll")
    public void findUser(){
        List<User> all = userRepository.findAll();
        for (User user : all) {
            System.out.println(user);
        }
    }
    @GetMapping("findId")
    public void getById() {
        User user = userRepository.findById("60fa987b8124bf51fa51d219").get();
        System.out.println(user);
    }
    @GetMapping("findUser")
    public void findUserList() {
        User user=new User();
        user.setName("lucy");
        Example<User> of = Example.of(user);
        User user1 = userRepository.findOne(of).get();
        System.out.println(user1);
    }
    //模糊查询
    @GetMapping("findLike")
    public void findUsersLikeName() {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().
                withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).
                withIgnoreCase(true);
        User user=new User();
        user.setName("l");
        Example<User> of = Example.of(user, exampleMatcher);
        List<User> all = userRepository.findAll(of);
        System.out.println(all);
    }
    @GetMapping("findPage")
    public void findUsersPage() {
        Sort age = Sort.by(Sort.Order.desc("age"));
        PageRequest pageRequest = PageRequest.of(0, 10,age);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().
                withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).
                withIgnoreCase(true);
        User user=new User();
        user.setName("l");
        Example<User> of = Example.of(user, exampleMatcher);
        Page<User> all = userRepository.findAll(of, pageRequest);
        System.out.println(all);
    }
    //修改
    @GetMapping("update")
    public void updateUser(){
        User user = userRepository.findById("60fa987b8124bf51fa51d219").get();
        user.setName("张三");
        user.setAge(30);
        User save = userRepository.save(user);
        System.out.println(save);
    }
    @GetMapping("delete")
    public void delete() {
        userRepository.deleteById("60fa987b8124bf51fa51d219");
    }
}
